#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2019/10/16 16:38
# @Author  : ZRD
# @File    : rsa_test.py

"""
https://blog.csdn.net/yangxiaodong88/article/details/80801278

https://www.cnblogs.com/Colin-Cai/p/8013009.html


"""

import rsa


# rsa加密
def rsaEncrypt(str):
    # 生成公钥、私钥
    (pubkey, privkey) = rsa.newkeys(1024)
    pubkeydata = pubkey.save_pkcs1()
    private_key = privkey.save_pkcs1()
    print("公钥pub  pubkey.save_pkcs1() : ", pubkeydata)
    print("私钥priv privkey.save_pkcs1(): ", private_key)

    with open("save_pkcs1.pub", 'wb') as f:
        f.write(pubkeydata)

    with open("privkey.pem", 'wb') as f:
        f.write(private_key)

    print("公钥pub: ", pubkey)
    print("私钥priv: ", privkey)
    # 明文编码格式
    content = str.encode('utf-8')
    # 公钥加密
    crypto = rsa.encrypt(content, pubkey)
    return (crypto, privkey)


# rsa解密
def rsaDecrypt(str, pk):
    # 私钥解密
    content = rsa.decrypt(str, pk)
    con = content.decode('utf-8')
    return con


def checkcrypt():
    """
    测试秘钥文件
    :return:
    """

    with open('save_pkcs1.pem', 'r') as f:
        pub_pkcs = f.read().encode()
    with open('serverprivkey.pem', 'r') as f:
        priv_pkcs = f.read().encode()
    # 加载公钥私钥
    public_key = rsa.PublicKey.load_pkcs1(pub_pkcs)
    private_key = rsa.PrivateKey.load_pkcs1(priv_pkcs)
    print(f'加载到的公钥: {public_key}')

    print(f'加载到的私钥{private_key}', )


if __name__ == '__main__':
    (a, b) = rsaEncrypt("hello")
    print('f加密后密文：{a}')

    content = rsaDecrypt(a, b)
    print('解密后明文：')
    print(content)
    checkcrypt()
